<!-- TableComponent.vue -->
<template>
  <!-- <div class="custom-table-container" :class="{ 'is-selected': selected }"> -->
  <node-view-wrapper as="div" data-drag-handle>
    <!-- <div class="table-toolbar" v-if="editable">
        <button @click="addRow">添加行</button>
        <button @click="removeRow">删除行</button>
      </div> -->

    <el-table :data="localData" border style="width: 100%">
      <el-table-column prop="date" label="日期" width="180">
        <template #default="scope">
          <input v-if="editable" v-model="scope.row.date" @input="updateData" />
          <span v-else>{{ scope.row.date }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="180">
        <template #default="scope">
          <input v-if="editable" v-model="scope.row.name" @input="updateData" />
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址">
        <template #default="scope">
          <input v-if="editable" v-model="scope.row.address" @input="updateData" />
          <span v-else>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
    </el-table>
    <node-view-content class="content" />
  </node-view-wrapper>

  <!-- </div> -->
</template>

<script setup>
import { NodeViewWrapper, NodeViewContent } from '@tiptap/vue-3'
import { ref, watch } from 'vue'

const props = defineProps({
  editor: Object,
  node: Object,
  decorations: Array,
  selected: Boolean,
  extension: Object,
  getPos: Function,
  updateAttributes: Function
})

const editable = ref(props.editor.isEditable)
const localData = ref([...props.node.attrs.data])

// 监听编辑器可编辑状态变化
watch(
  () => props.editor.isEditable,
  newVal => {
    editable.value = newVal
  }
)

// 更新数据到编辑器
const updateData = () => {
  props.updateAttributes({ data: [...localData.value] })
}

// 添加行
const addRow = () => {
  localData.value.push({ date: '', name: '', address: '' })
  updateData()
}

// 删除行
const removeRow = () => {
  if (localData.value.length > 1) {
    localData.value.pop()
    updateData()
  }
}
</script>

<style>
.custom-table-container {
  margin: 1em 0;
  position: relative;
}

.custom-table-container.is-selected {
  outline: 2px solid #4a9ff9;
}

.table-toolbar {
  margin-bottom: 8px;
}

.table-toolbar button {
  margin-right: 8px;
  padding: 4px 8px;
  background: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 3px;
  cursor: pointer;
}

.el-table .cell input {
  width: 100%;
  border: none;
  padding: 0;
  margin: 0;
  background: transparent;
}
</style>
